﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Newtonsoft.Json;

namespace WPF_DragDrop_UI_Demo
{
    public partial class MainWindow : Window
    {
        public MainViewModel ViewModel { get; set; }
        private RegionManager _regionManager; // 区域管理器

        public MainWindow()
        {
            InitializeComponent();
            ViewModel = new MainViewModel();
            DataContext = ViewModel; // 设置数据上下文
            _regionManager = new RegionManager(); // 初始化区域管理器
        }

        // =================== DragDrop 相关方法 ===================
        private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var listBox = sender as ListBox;
            var item = FindAncestor<ListBoxItem>((DependencyObject)e.OriginalSource);
            if (item != null)
            {
                var data = item.DataContext as SensorViewModel;
                DragDrop.DoDragDrop(listBox, data, DragDropEffects.Move);
            }
        }

        private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            while (current != null)
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            return null;
        }

        private void Region_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = e.Data.GetDataPresent(typeof(SensorViewModel)) ? DragDropEffects.Move : DragDropEffects.None;
            e.Handled = true;
        }

        private void Region_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(SensorViewModel)))
            {
                var sensorData = e.Data.GetData(typeof(SensorViewModel)) as SensorViewModel;
                var targetRegion = sender as Border;

                if (targetRegion != null && sensorData != null)
                {
                    string regionName = GetRegionName(targetRegion); // 获取区域名称
                    _regionManager.AddDataToRegion(regionName, sensorData); // 将数据添加到区域管理器
                    AddOrUpdateDataGridRow(targetRegion, sensorData); // 更新 DataGrid 行
                }
            }
        }

        private string GetRegionName(Border region)
        {
            if (region == Region1) return "Region1";
            if (region == Region2) return "Region2";
            if (region == Region3) return "Region3";
            return null;
        }

        // 更新 DataGrid 行
        private void AddOrUpdateDataGridRow(Border targetRegion, SensorViewModel sensorData)
        {
            if (targetRegion.Child is DataGrid dataGrid)
            {
                dataGrid.AutoGenerateColumns = false;
                // 如果 DataGrid 的列尚未定义，则创建固定的四列
                if (dataGrid.Columns.Count == 0)
                {
                    dataGrid.Columns.Add(new DataGridTextColumn
                    {
                        Header = "传感器名称",
                        Binding = new Binding("SensorName")
                    });

                    dataGrid.Columns.Add(new DataGridTextColumn
                    {
                        Header = "时间",
                        Binding = new Binding("LatestDataPoint.Timestamp")
                    });

                    dataGrid.Columns.Add(new DataGridTextColumn
                    {
                        Header = "值",
                        Binding = new Binding("LatestDataPoint.Value")
                    });

                    dataGrid.Columns.Add(new DataGridTextColumn
                    {
                        Header = "单位",
                        Binding = new Binding("LatestDataPoint.Unit")
                    });
                }

                // 绑定到 ObservableCollection<SensorViewModel>
                if (dataGrid.ItemsSource == null)
                {
                    var sensorCollection = new ObservableCollection<SensorViewModel>();
                    dataGrid.ItemsSource = sensorCollection;
                }

                var sensorViewModels = dataGrid.ItemsSource as ObservableCollection<SensorViewModel>;

                // 检查传感器是否存在，存在则更新，否则添加新行
                var existingSensor = sensorViewModels.FirstOrDefault(s => s.SensorName == sensorData.SensorName);
                if (existingSensor != null)
                {
                    existingSensor.LatestDataPoint = sensorData.LatestDataPoint; // 更新已有传感器的数据
                }
                else
                {
                    sensorViewModels.Add(sensorData); // 添加新传感器数据
                }
            }
        }

        private void SensorList_DragOver(object sender, DragEventArgs e)
        {
            Region_DragOver(sender, e); // 重用 DragOver 逻辑
        }

        // =================== ContextMenu 相关方法 ===================
        private void Region_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            Border selectedRegion = sender as Border;
            ContextMenu contextMenu = CreateContextMenu(selectedRegion);
            selectedRegion.ContextMenu = contextMenu;
            contextMenu.IsOpen = true;
        }

        private ContextMenu CreateContextMenu(Border region)
        {
            ContextMenu contextMenu = new ContextMenu();

            MenuItem bodePlotItem = new MenuItem { Header = "波特图" };
            bodePlotItem.Click += (s, args) => UpdateRegionContent(region, "波特图");

            MenuItem nyquistPlotItem = new MenuItem { Header = "奈氏图" };
            nyquistPlotItem.Click += (s, args) => UpdateRegionContent(region, "奈氏图");

            MenuItem dataTableItem = new MenuItem { Header = "数据表" };
            dataTableItem.Click += (s, args) => UpdateRegionContent(region, "数据表");

            contextMenu.Items.Add(bodePlotItem);
            contextMenu.Items.Add(nyquistPlotItem);
            contextMenu.Items.Add(dataTableItem);

            return contextMenu;
        }

        private void UpdateRegionContent(Border region, string contentType)
        {
            switch (contentType)
            {
                case "波特图":
                case "奈氏图":
                    region.Child = new TextBlock
                    {
                        Text = contentType,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center
                    };
                    break;
                case "数据表":
                    DataGrid dataGrid = new DataGrid
                    {
                        AutoGenerateColumns = true,
                        HorizontalAlignment = HorizontalAlignment.Stretch,
                        VerticalAlignment = VerticalAlignment.Stretch
                    };
                    dataGrid.Drop += Region_Drop; // 添加 Drop 事件
                    region.Child = dataGrid;

                    // 获取区域数据并填充到 DataGrid
                    var regionName = GetRegionName(region);
                    var sensorDataList = _regionManager.GetDataForRegion(regionName);
                    if (sensorDataList != null)
                    {
                        foreach (var sensorData in sensorDataList)
                        {
                            AddOrUpdateDataGridRow(region, sensorData);
                        }
                    }
                    break;
            }
        }

        // =================== 布局保存和加载相关方法 ===================
        private void SaveLayout_Click(object sender, RoutedEventArgs e)
        {
            var layout = new ControlLayout
            {
                RegionLayouts = new List<RegionLayout>
                {
                    new RegionLayout { RegionName = "Region1", ControlType = GetControlType(Region1) },
                    new RegionLayout { RegionName = "Region2", ControlType = GetControlType(Region2) },
                    new RegionLayout { RegionName = "Region3", ControlType = GetControlType(Region3) }
                },
                Row1Height = Row1.Height.Value,
                Row2Height = Row2.Height.Value,
                Column1Width = Column1.Width.Value,
                Column2Width = Column2.Width.Value
            };

            string json = JsonConvert.SerializeObject(layout, Formatting.Indented);
            File.WriteAllText("layout.json", json);
            MessageBox.Show("布局已保存！");
        }

        private void LoadLayout_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists("layout.json"))
            {
                string json = File.ReadAllText("layout.json");
                var layout = JsonConvert.DeserializeObject<ControlLayout>(json);

                Row1.Height = new GridLength(layout.Row1Height, GridUnitType.Star);
                Row2.Height = new GridLength(layout.Row2Height, GridUnitType.Star);
                Column1.Width = new GridLength(layout.Column1Width, GridUnitType.Star);
                Column2.Width = new GridLength(layout.Column2Width, GridUnitType.Star);

                foreach (var regionLayout in layout.RegionLayouts)
                {
                    Border targetRegion = FindRegionByName(regionLayout.RegionName);
                    if (targetRegion != null)
                    {
                        UpdateRegionContent(targetRegion, regionLayout.ControlType);
                    }
                }

                MessageBox.Show("布局已加载！");
            }
            else
            {
                MessageBox.Show("未找到布局文件！");
            }
        }

        private string GetControlType(Border region)
        {
            if (region.Child is TextBlock textBlock)
                return textBlock.Text;
            if (region.Child is DataGrid)
                return "数据表";

            return "未知";
        }

        private Border FindRegionByName(string regionName)
        {
            switch (regionName)
            {
                case "Region1":
                    return Region1;
                case "Region2":
                    return Region2;
                case "Region3":
                    return Region3;
                default:
                    return null;
            }
        }
    }

    // =================== 布局相关类 ===================
    public class ControlLayout
    {
        public double Row1Height { get; set; }
        public double Row2Height { get; set; }
        public double Column1Width { get; set; }
        public double Column2Width { get; set; }
        public List<RegionLayout> RegionLayouts { get; set; }
    }

    public class RegionLayout
    {
        public string RegionName { get; set; }
        public string ControlType { get; set; }
    }
}
